package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jack
 * @data 2023 16:31
 */
@Service
@Transactional
@Slf4j
public class FreemarkerServiceImpl implements FreemarkerService{

    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 构建文章详情页
     *
     * @param content   文章内容
     * @param articleId 文章id
     */
    @Override
//    @Async      //本质是aop动态代理，方法的调用交给springBoot内置线程池来处理
    @Transactional
    public void buildDetailsPage(String content, Long articleId) {
        try {
            ApArticle article = apArticleMapper.selectById(articleId);
            if (article == null)
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);


            //1. 拿到模板
            Template template = configuration.getTemplate("article.ftl");
            //2. 基于模板来合成页面
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            StringWriter sw = new StringWriter();
            template.process(map, sw);

            //3. 将合成好的页面上传到minIO
            InputStream is = new ByteArrayInputStream(sw.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", articleId+"", is);

            //4. 将minIO返回的url保存到ap_article表的static_url字段上
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);

            //发送消息通知search微服务，进行文章信息的ES数据同步
            JSONObject articleJSONObject = JSONObject.parseObject(JSON.toJSONString(article));
            articleJSONObject.put("content",content);
            kafkaTemplate.send("ES_ARTICLE_ASYNC_TOPIC",articleJSONObject.toJSONString());

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
